package cn.renxuan;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

public class CommonUtil {
    public static void sleepMillis(long millis) {
        try {
            TimeUnit.MILLISECONDS.sleep(millis);
        } catch (InterruptedException e) {
            printThreadLog(e.getMessage());
        }
    }

    /*
     * 线程暂停秒数
     */
    public static void sleepSecond(long seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            printThreadLog(e.getMessage());
        }
    }

    public static String getTimestamp() {
        LocalTime time = LocalTime.now();
        return time.format(DateTimeFormatter.ofPattern("[HH:mm:ss SSS]"));
    }

    /*
     * 打印带有线程信息的日志
     */
    public static void printThreadLog(String message) {
        // 时间戳 | 线程id | 线程名 | 日志信息
        String result = new StringJoiner(" | ")
                // .add(String.valueOf(System.currentTimeMillis()))
                .add(getTimestamp())
                .add(String.format("%2d", Thread.currentThread().getId()))
                .add(Thread.currentThread().getName())
                .add(message).toString();

        System.out.println(result);
    }
}
